const fs = require('fs');

const getDataFromList = (list, attr, key) => {
    let min = Number.MAX_SAFE_INTEGER;
    let max = Number.MIN_SAFE_INTEGER;
    let total = 0;
    list.forEach(item => {
        const v = item[attr];
        v > max && (max = v);
        v < min && (min = v);
        total += v;
    });
    return {
        [key]: {
            min,
            max,
            total,
        },
    };
}

const getEXData = (players, attr, range) => {
    let min = Number.MAX_SAFE_INTEGER;
    let max = Number.MIN_SAFE_INTEGER;
    let result = {
        min: {},
        max: {},
    };
    Object.keys(players).forEach(name => {
        const count = players[name].filter(item => item.totalData[attr][range]).length;
        if (count < min) {
            min = count;
            result.min.name = [name];
            result.min.count = count;
        }
        if (count === min) {
            result.min.name.push(name);
        }
        if (count > max) {
            max = count;
            result.max.name = [name];
            result.max.count = count;
        }
        if (count === max) {
            result.max.name.push(name);
        }
    });
    result.min.text = Array.from(new Set(result.min.name)).join('、') + `；局数${result.min.count}`;
    result.max.text = Array.from(new Set(result.max.name)).join('、') + `；局数${result.max.count}`;
    return result;
}

module.exports = (playerList) => {
    const data = JSON.parse(fs.readFileSync('./src/data.json').toString());
    const result = {};
    result.total = data.list.length;
    result.win = data.list.filter(item => item.win === 'Win').length;
    result.list = [];
    result.players = {};
    data.list.forEach(item => {
        const myTeam = item.battle_detail.team_details.find(team => team.teamId === item.team_id);
        const myTeamPlayers = item.battle_detail.player_details.filter(player => player.teamId === item.team_id)
            .map(player => {
                // 防止0人头
                player.damagePerKill = player.totalDamageToChampions / (player.championsKilled + 1);
                player.damagePerGold = player.totalDamageToChampions / player.goldEarned;
                player.takenPerGold = player.totalDamageTaken / player.goldEarned;
                return player;
            });
        const battleDetail = {
            win: item.win === 'Win',
            startTime: item.battle_detail.game_start_time,
            playTime: item.battle_detail.game_time_played,
            k: myTeam.totalKills,
            d: myTeam.totalDeaths,
            a: myTeam.totalAssists,
            gold: myTeam.totalGoldEarned,
            turrets: myTeam.totalTurretsKilled,
            isSurrender: item.battle_detail.team_details.some(team => team.isSurrender === 1),
            players: [],
            totalData: {
                ...getDataFromList(myTeamPlayers, 'championsKilled', 'k'),
                ...getDataFromList(myTeamPlayers, 'numDeaths','d'),
                ...getDataFromList(myTeamPlayers, 'assists','a'),
                ...getDataFromList(myTeamPlayers, 'goldEarned','gold'),
                ...getDataFromList(myTeamPlayers, 'totalDamageTaken','taken'),
                ...getDataFromList(myTeamPlayers, 'totalDamageToChampions','damage'),
                ...getDataFromList(myTeamPlayers, 'gameScore','score'),
                ...getDataFromList(myTeamPlayers, 'damagePerKill','dpk'),
                ...getDataFromList(myTeamPlayers, 'damagePerGold','dpg'),
                ...getDataFromList(myTeamPlayers, 'takenPerGold','tpg'),
            },
        };
        myTeamPlayers
            .filter(player => player.teamId === item.team_id)
            .forEach(player => {
                const name = decodeURI(player.name);
                const totalData = battleDetail.totalData;
                const validPlayer = {
                    name,
                    win: item.win === 'Win',
                    k: player.championsKilled,
                    d: player.numDeaths,
                    a: player.assists,
                    score: player.gameScore,
                    mvp: player.battleHonour.isMvp === 1,
                    svp: player.battleHonour.isSvp === 1,
                    afk: player.wasAfk,
                    gold: player.goldEarned,
                    taken: player.totalDamageTaken,
                    damage: player.totalDamageToChampions,
                    health: player.totalHealth,
                    deathTime: player.totalTimeSpentDead,
                    cs: player.allMinionsKilled,
                    turrets: player.turretsKilled,
                    dpk: player.damagePerKill,
                    dpg: player.damagePerGold,
                    tpg: player.takenPerGold,
                    totalData: {},
                };
                ['k', 'd', 'a', 'gold', 'taken', 'damage', 'score', 'dpk', 'dpg', 'tpg'].forEach(key => {
                    validPlayer.totalData[key] = {
                        min: totalData[key].min === validPlayer[key],
                        max: totalData[key].max === validPlayer[key],
                        percent: validPlayer[key] / totalData[key].total,
                    };
                });
                if (playerList.includes(name)) {
                    battleDetail.players.push(validPlayer);
                    if (result.players[name]) {
                        result.players[name].push(validPlayer);
                    } else {
                        result.players[name] = [validPlayer];
                    }
                }
            });
        result.list.push(battleDetail);
    });

    fs.writeFileSync('./src/result.json', JSON.stringify(result, null, 2));

    console.log(`学习成果：总${result.total}，胜${result.win}，负${result.total - result.win}，胜率 ${(result.win / result.total * 100).toFixed(2)}%`);
    console.log(`学习过程：${[...result.list].reverse().map(item => item.win ? '√' : '×').join('')}`);
    console.log('个人统计：')
    Object.keys(result.players).forEach(name => {
        const list = result.players[name];
        const vpCount = list.filter(item => item.mvp || item.svp).length;
        console.log(
            `${name} -> ` +
            `总${list.length}，胜${list.filter(item => item.win).length}，负${list.filter(item => !item.win).length}，胜率${(list.filter(item => item.win).length / list.length * 100).toFixed(2)}%、` +
            `vp率：${(vpCount / list.length * 100).toFixed(2)}%、` +
            `最高击杀：${list.filter(item => item.totalData.k.max).length}、` +
            `最低击杀：${list.filter(item => item.totalData.k.min).length}、` +
            `最高死亡：${list.filter(item => item.totalData.d.max).length}、` +
            `最低死亡：${list.filter(item => item.totalData.d.min).length}、` +
            `最高伤害：${list.filter(item => item.totalData.damage.max).length}、` +
            `最低伤害：${list.filter(item => item.totalData.damage.min).length}、` +
            `最高经济：${list.filter(item => item.totalData.gold.max).length}、` +
            `最低经济：${list.filter(item => item.totalData.gold.min).length}、`
        );
    });

    console.log(`各项总结：`);
    console.log(`击杀最多：${getEXData(result.players, 'k', 'max').max.text}`);
    console.log(`死亡最多：${getEXData(result.players, 'd', 'max').max.text}`);
    console.log(`伤害最高：${getEXData(result.players, 'damage', 'max').max.text}`);
    console.log(`坦克爸爸：${getEXData(result.players, 'taken', 'max').max.text}`);
    console.log(`助攻最多：${getEXData(result.players, 'a', 'max').max.text}`);
    console.log(`K头怪(伤害/人头最低)：${getEXData(result.players, 'dpk', 'min').max.text}`);
    console.log(`K不到头(伤害/人头最高)：${getEXData(result.players, 'dpk', 'max').max.text}`);
    console.log(`拿钱输出(伤害/经济最高)：${getEXData(result.players, 'dpg', 'max').max.text}`);
    console.log(`拿钱不输出(伤害/经济最低)：${getEXData(result.players, 'dpg', 'min').max.text}`);
    console.log(`拿钱承伤(承伤/经济最高)：${getEXData(result.players, 'tpg', 'max').max.text}`);
    console.log(`拿钱不承伤(承伤/经济最低)：${getEXData(result.players, 'tpg', 'min').max.text}`);
}

